<!DOCTYPE html>
<html lang="zh">
<head>
    <title>Sa-SSO-Server 认证中心-登录</title>
    <meta charset="utf-8">
    <base th:href="@{/}" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <style>
        *{margin: 0; padding: 0;}
        body{font-family: Helvetica Neue,Helvetica,PingFang SC,Tahoma,Arial,sans-serif;}
        ::-webkit-input-placeholder{color: #ccc;}

        /* 视图盒子 */
        .view-box{position: relative; width: 100vw; height: 100vh; overflow: hidden;}
        /* 背景 EAEFF3 */
        .bg-1{height: 100%; background: #c0cCf4;}

        /* 内容盒子 */
        .content-box{position: absolute; width: 100vw; height: 100vh; top: 0px;}

        /* 登录盒子 */
        /* .login-box{width: 400px; height: 400px; position: absolute; left: calc(50% - 200px); top: calc(50% - 200px); max-width: 90%; } */
        .login-box{width: 400px; margin: auto; max-width: 90%; height: 100%;}
        .login-box{display: flex; align-items: center; text-align: center;}

        /* 表单 */
        .from-box{flex: 1; padding: 20px 50px; background-color: #FFF;}
        .from-box{border-radius: 1px; box-shadow: 1px 1px 20px #666;}
        .from-title{margin-top: 20px; margin-bottom: 30px; text-align: center;}

        /* 输入框 */
        .from-item{border: 0px #000 solid; margin-bottom: 15px;}
        .s-input{width: 100%; line-height: 32px; height: 32px; text-indent: 1em; outline: 0; border: 1px #ccc solid; border-radius: 3px; transition: all 0.2s;}
        .s-input{font-size: 12px;}
        .s-input:focus{border-color: #409eff}

        /* 登录按钮 */
        .s-btn{ text-indent: 0; cursor: pointer; background-color: #409EFF; border-color: #409EFF; color: #FFF;}
        .s-btn:hover{background-color: #50aEFF;}

        /* 重置按钮 */
        .reset-box{text-align: left; font-size: 12px;}
        .reset-box a{text-decoration: none;}
        .reset-box a:hover{text-decoration: underline;}

        /* loading框样式 */
        .ajax-layer-load.layui-layer-dialog{min-width: 0px !important; background-color: rgba(0,0,0,0.85);}
        .ajax-layer-load.layui-layer-dialog .layui-layer-content{padding: 10px 20px 10px 40px; color: #FFF;}
        .ajax-layer-load.layui-layer-dialog .layui-layer-content .layui-layer-ico{width: 20px; height: 20px; background-size: 20px 20px; top: 12px; }
    </style>
</head>
<body>
<div class="view-box">
    <div class="bg-1"></div>
    <div class="content-box">
        <div class="login-box">
            <div class="from-box">
                <h2 class="from-title">Sa-SSO-Server 认证中心（前后端分离版）</h2>
                <div class="from-item">
                    <input class="s-input" name="name" placeholder="请输入账号" />
                </div>
                <div class="from-item">
                    <input class="s-input" name="pwd" type="password" placeholder="请输入密码" />
                </div>
                <div class="from-item">
                    <button class="s-input s-btn login-btn">登录</button>
                </div>
                <div class="from-item reset-box">
                    <a href="javascript: location.reload();" >刷新</a>
                </div>
            </div>
        </div>
    </div>
    <!-- 底部 版权 -->
    <div style="position: absolute; bottom: 40px; width: 100%; text-align: center; color: #666;">
        This page is provided by Sa-Token-SSO
    </div>
</div>

<!-- scripts -->
<script src="https://unpkg.zhimg.com/jquery@3.4.1/dist/jquery.min.js"></script>
<script src="https://www.layuicdn.com/layer-v3.1.1/layer.js"></script>
<script>

    // 服务端地址
    var baseUrl = "http://127.0.0.1:5566";

    // sa
    var sa = {};

    // 打开loading
    sa.loading = function(msg) {
        layer.closeAll();	// 开始前先把所有弹窗关了
        return layer.msg(msg, {icon: 16, shade: 0.3, time: 1000 * 20, skin: 'ajax-layer-load'});
    };

    // 隐藏loading
    sa.hideLoading = function() {
        layer.closeAll();
    };

    // 封装一下Ajax
    sa.ajax = function(url, data, successFn) {
        $.ajax({
            url: baseUrl + url,
            type: "post",
            data: data,
            dataType: 'json',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'Authorization': localStorage.getItem('Authorization')
            },
            success: function(res){
                console.log('返回数据：', res);
                successFn(res);
            },
            error: function(xhr, type, errorThrown){
                if(xhr.status == 0){
                    return alert('无法连接到服务器，请检查网络');
                }
                return alert("异常：" + JSON.stringify(xhr));
            }
        });
    }

    // ----------------------------------- 相关事件 -----------------------------------

    // 检查当前是否已经登录，如果已登录则直接开始跳转，如果未登录则等待用户输入账号密码
    var pData = {
        client: getParam('client', ''),
        redirect: getParam('redirect', ''),
        mode: getParam('mode', '')
    };
    sa.ajax("/sso/redirectUrl/ticket", pData, function(res) {
        if(res.success) {
            // 已登录，并且redirect地址有效，开始跳转
            location.href = res.data;
        } else {
            layer.alert(res.msg);
        }
    })

    // 登录
    $('.login-btn').click(function(){
        sa.loading("正在登录...");
        // 开始登录
        var data = {
            authType: "password",
            authParamMap: JSON.stringify({
                username: $('[name=name]').val(),
                password: $('[name=pwd]').val()
            })
        };
        sa.ajax("/sso/doLogin", data, function(res) {
            sa.hideLoading();
            if(res.success) {
                localStorage.setItem('Authorization', res.data);
                layer.msg('登录成功', {anim: 0, icon: 6 });
                setTimeout(function() {
                    location.reload();
                }, 800);
            } else {
                layer.msg(res.msg, {anim: 6, icon: 2 });
            }
        })
    });


    // 绑定回车事件
    $('[name=name],[name=pwd]').bind('keypress', function(event){
        if(event.keyCode == "13") {
            $('.login-btn').click();
        }
    });

    // 输入框获取焦点
    $("[name=name]").focus();

    // 从url中查询到指定名称的参数值
    function getParam(name, defaultValue){
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i=0;i<vars.length;i++) {
            var pair = vars[i].split("=");
            if(pair[0] == name){return pair[1] + (pair[2] ? '=' + pair[2] : '');}
        }
        return(defaultValue == undefined ? null : defaultValue);
    }

    // 打印信息
    var str = "This page is provided by Sa-Token, Please refer to: " + "https://sa-token.cc/";
    console.log(str);
</script>

</body>
</html>